package org.example.cet.demos.interceptor;

import org.example.cet.demos.domain.Result;
import org.example.cet.demos.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 获取请求的URL
        String url = req.getRequestURL().toString();
        // 如果请求的URL包含"login"，则直接放行
        if (url.contains("login")) {
            return true;
        }
        // 从请求头中获取JWT
        String jwt = req.getHeader("token");

        // 如果JWT为空
        if (!StringUtils.hasLength(jwt)) {
            // 返回未登录的错误信息
            Result error = Result.error(0, "NOT_LOGIN");
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(error.toString());
            return false;
        }
        try {
            // 解析JWT
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            // 解析失败，返回未登录的错误信息
            e.printStackTrace();
            Result error = Result.error(0, "NOT_LOGIN");
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(error.toString());
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle ... ");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion... ");
    }
}